package com.luoxiang.socialandroid.activity;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.DOMAIN;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ClipboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.app.MyAppliaction;
import com.luoxiang.socialandroid.base.BaseActivity;
import com.luoxiang.socialandroid.bean.Dequity;
import com.luoxiang.socialandroid.bean.InviteBean;
import com.luoxiang.socialandroid.bean.InviteUrlBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.UserInfoBean;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils2;

import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class RecommendActivity extends BaseActivity {
    private ImageView icon_back, im_icon, im_weixin, im_qq, im_fuzhilianjie, im_erweima;
    private TextView tx_name, tx_inviteuser, tx_inviteaward, guize, tishi,textRechargeCount,textHostCount;
    private RelativeLayout r_inviteuser, r_inviteaward,relativeRechargeUser,relativeAuthenticationUser;
    private String token;
    private double credit;
    private String url = "https://dahuixiong.oss-cn-shenzhen.aliyuncs.com/";
    private InviteUrlBean bean;
    private ScrollView scrollView;
    private ConstraintLayout constraintTop;
    private ImageView icon_back1;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @SuppressLint("CheckResult")
    @Override
    protected void initListener() {
        icon_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        r_inviteuser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RecommendActivity.this, InviteuserActivity.class);
                intent.putExtra("type",0);
                startActivity(intent);
            }
        });
        relativeAuthenticationUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RecommendActivity.this, InviteuserActivity.class);
                intent.putExtra("type",1);
                startActivity(intent);
            }
        });
        relativeRechargeUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RecommendActivity.this, InviteuserActivity.class);
                intent.putExtra("type",2);
                startActivity(intent);
            }
        });
        r_inviteaward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RecommendActivity.this, InviteawardActivity.class);
                intent.putExtra("credit", credit);
                startActivity(intent);
            }
        });
        im_fuzhilianjie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (bean == null || bean.getData().getInviteUrl() == null) {
                    ToastUtils.showShort(R.string.mi_fuzhishibai);
                    return;
                }
                ClipboardUtils.copyText(bean.getData().getInviteUrl());
                ToastUtils.showShort(R.string.mi_copy_success);
            }
        });
        im_qq.setOnClickListener(v -> {
            if (!isQQClientAvailable(RecommendActivity.this)) {
                ToastUtils.showShort(R.string.mi_meiyouqq);
            } else {
                if (bean == null || bean.getData().getInviteUrl() == null) {
                    ToastUtils.showShort(R.string.mi_fenxiangshibai);
                    return;
                }
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_SEND);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, bean.getData().getInviteUrl());
                startActivity(intent);
            }

        });
        im_weixin.setOnClickListener(view -> {
            if (!isWeixinAvilible(RecommendActivity.this)) {
                ToastUtils.showShort(R.string.mi_meiyouweixin);
            } else {
                if (bean == null || bean.getData().getInviteUrl() == null) {
                    ToastUtils.showShort(R.string.mi_fenxiangshibai);
                    return;
                }
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_SEND);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, bean.getData().getInviteUrl());
                startActivity(intent);
            }
        });
        im_erweima.setOnClickListener(v -> {
            if (bean != null) {
                if (bean.getData() != null) {
                    Intent intent = new Intent(RecommendActivity.this, ShareActivity.class);
                    intent.putExtra("erweimaUrl", DOMAIN + bean.getData().getQrCodePath());
                    startActivity(intent);
                }
            } else {
                ToastUtils.showShort(R.string.mi_zanweishengchengerweima);
                return;
            }


        });
        scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY <= 0) {
                    constraintTop.setVisibility(View.GONE);
                } else {
                    constraintTop.setVisibility(View.VISIBLE);
                }
            }
        });
        icon_back1.setOnClickListener(v -> finish());
    }

    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 判断qq是否可用
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;

    }


    @Override
    protected void initLayout(Bundle savedInstanceState) {
        setContentView(R.layout.activity_recommend);
        setStatusBarTranslucent();
    }

    @Override
    protected void initView() {
        showLoading();
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        icon_back = findViewById(R.id.icon_back);
        im_icon = findViewById(R.id.im_icon);
        im_weixin = findViewById(R.id.im_weixin);
        icon_back1 = findViewById(R.id.icon_back1);
        constraintTop = findViewById(R.id.constraintTop);
        im_qq = findViewById(R.id.im_qq);
        im_fuzhilianjie = findViewById(R.id.im_fuzhilianjie);
        tx_name = findViewById(R.id.tx_name);
        tx_inviteuser = findViewById(R.id.tx_inviteuser);
        tx_inviteaward = findViewById(R.id.tx_inviteaward);
        r_inviteuser = findViewById(R.id.r_inviteuser);
        r_inviteaward = findViewById(R.id.r_inviteaward);
        relativeRechargeUser = findViewById(R.id.relativeRechargeUser);
        relativeAuthenticationUser = findViewById(R.id.relativeAuthenticationUser);
        im_erweima = findViewById(R.id.im_erweima);
        scrollView = findViewById(R.id.scrollView);
        guize = findViewById(R.id.guize);
        tishi = findViewById(R.id.tishi);
        textRechargeCount = findViewById(R.id.textRechargeCount);
        textHostCount = findViewById(R.id.textHostCount);
        im_icon.bringToFront();
        getHomeUserInfo(token, EXTRA);
        getInviteInfo(token, EXTRA);
        getInviteUrl(token, EXTRA);
    }

    private void getInviteUrl(String token, String extra) {
        getRequest();
        NetUtils2.getInstance().getApiService().getInviteUrl(token, extra)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            LogUtils.i("decryptStrfenxiang", decryptStr);
                            Gson gson = new Gson();
                            bean = gson.fromJson(decryptStr, InviteUrlBean.class);
                        } catch (Exception e) {
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getInviteInfo(String token, String extra) {
        NetUtils2.getInstance().getApiService().getInviteInfo(token, extra)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        clearLoading();
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            LogUtils.i("decryptStr0", decryptStr);
                            Gson gson = new Gson();
                            InviteBean bean = gson.fromJson(decryptStr, InviteBean.class);
                            credit = bean.getData().getInvite().getInviteCredit();
                            tx_inviteuser.setText(bean.getData().getInvite().getInviteCount() + getString(R.string.mi_ren));
                            textRechargeCount.setText(bean.getData().getInvite().getRechargeCount() + getString(R.string.mi_ren));
                            textHostCount.setText(bean.getData().getInvite().getHostCount() + getString(R.string.mi_ren));
                            tx_inviteaward.setText(credit + getString(R.string.mi_fen));
                            if (bean.getData().getInvite().getDequity().size() >= 1) {
                                StringBuilder sb = new StringBuilder();
                                for (String content : bean.getData().getInvite().getDequity().get(0).getContent()) {
                                    sb.append(content).append("\n");
                                }
                                guize.setText(sb.toString());
                            }
                            if (bean.getData().getInvite().getDequity().size() >= 2) {
                                StringBuilder sb = new StringBuilder();
                                for (String content : bean.getData().getInvite().getDequity().get(1).getContent()) {
                                    sb.append(content).append("\n");
                                }
                                tishi.setText(sb.toString());
                            }
                        } catch (Exception e) {
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        clearLoading();
                    }

                    @Override
                    public void onComplete() {
                        clearLoading();
                    }
                });
    }

    private void getHomeUserInfo(String token, String extra) {
        NetUtils2.getInstance().getApiService().getHomeUserInfo(token, extra)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            LogUtils.i("decryptStr0", decryptStr);
                            Gson gson = new Gson();

                            UserInfoBean bean = gson.fromJson(decryptStr, UserInfoBean.class);
                            Glide.with(MyAppliaction.getContext())
                                    .load(url + bean.getData().getUser().getIcon())
                                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                                    .into(im_icon);
                            tx_name.setText(bean.getData().getUser().getName());
                        } catch (Exception e) {
                            LogUtils.i("decryptStr0", e.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
